package com.graduation.project.handler;

import com.alibaba.fastjson.JSON;
import com.graduation.project.utils.ResultUtil;
import com.graduation.project.utils.WebUtil;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 卑微小峰
 * @date 2022/10/15
 * 认证失败处理器
 */
@Component
public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        ResultUtil result = new ResultUtil(HttpStatus.UNAUTHORIZED.value(), "用户认证失败，请重新登录");

        // 处理异常
        WebUtil.renderString(response, JSON.toJSONString(result));
    }
}
